package com.example.webproject.Controller;

import com.example.webproject.entity.User;
import com.example.webproject.repository.UserRepository;
import com.example.webproject.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author hhs
 * @Description
 * @date 2022/12/7 0:24
 */
@CrossOrigin(origins = "http://127.0.0.1:5500/")
@RestController
public class IndexController {
    @GetMapping("/")
    public String index(){
//        int i=9/0;
//        模拟抛出异 常，跳转到其他页面场景
        return "index";
    }

    @Autowired
    private UserService userService;
    @Autowired
    private UserRepository userRepository;

    @GetMapping("/user")
    public ResponseEntity<List<User>> getUser(){
        List<User> users = userService.listUser();
        return new ResponseEntity<>(users, HttpStatus.OK);
    }
    @GetMapping("/user/{id}")
    public ResponseEntity<User> getUser(@PathVariable("id") long id){
        User users = userService.getUser(id);
        return new ResponseEntity(users, HttpStatus.OK);
    }
    @PostMapping("/user")
    public ResponseEntity<User> saveUser(@RequestBody User user){
        userService.saveUser(user);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping("/user/{id}")
    public  ResponseEntity<User> updateUser(@PathVariable("id")long id,@RequestBody User user){

        userService.updateUser(id,user);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @DeleteMapping("/user/{id}")
    public  ResponseEntity<HttpStatus> deleteUser(@PathVariable("id")Long id){
        userService.deleteUser(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
}
